//
//  LHImagePickerController.m
//  LHImagePicker
//
//  Created by 刘辉 lewis on 2018/6/13.
//  Copyright © 2018年 刘辉 lewis. All rights reserved.
//

#import "LHImagePickerController.h"
#import "LHImagePickerManager.h"
#import "LHCustomTitleView.h"
#import "LHImageViewCell.h"
#import "LHReusableFooterView.h"
#import "LHCameraAuthoritymanager.h"
#import "UIBarButtonItem+item.h"
#import "LHImagePickerHeader.h"
@interface LHImagePickerController ()<UICollectionViewDelegate,UICollectionViewDataSource,LHImageViewCellDelegate,UICollectionViewDelegateFlowLayout,LHCustomTitleViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong) UICollectionView          *collectionView;
@property(nonatomic,strong) LHCustomTitleView         *chooseTitleView;
/** 数据源数组 */
@property(nonatomic,strong) NSMutableArray<PHAsset*>  *dataSourceArray;
/** 已选择的PHAsset数组 */
@property(nonatomic,strong) NSMutableArray<PHAsset*>  *selectedAssetArray;
@property(nonatomic,strong) UIVisualEffectView        *toolbar;
@property(nonatomic,strong) UIButton                  *nextStepBtn;
@property(nonatomic,strong) UIButton                  *oringalImgBtn;
@end

@implementation LHImagePickerController

static NSString *kLHImagePickerCellIdentifier            = @"kLHImagePickerCellIdentifier";
static NSString *kLHImagePickerReuseFooterViewIdentifier = @"kLHImagePickerReuseFooterViewIdentifier";

#pragma mark - lazy loading
-(UIButton*)nextStepBtn{
    if (_nextStepBtn==nil) {
        _nextStepBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [_nextStepBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_nextStepBtn setBackgroundColor:[UIColor orangeColor]];
        _nextStepBtn.hidden=YES;
        [_nextStepBtn addTarget:self action:@selector(nextStepBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        if (KIsiPhoneX) {
            _nextStepBtn.frame=CGRectMake([UIScreen mainScreen].bounds.size.width-95, 12, 80, 30);
            _nextStepBtn.titleLabel.font=[UIFont systemFontOfSize:16];
        }else{
            _nextStepBtn.frame=CGRectMake([UIScreen mainScreen].bounds.size.width-95, 7, 80, 30);
            _nextStepBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        }
        _nextStepBtn.layer.cornerRadius=5;
        _nextStepBtn.layer.masksToBounds=YES;
    }
    return _nextStepBtn;
}
-(UIVisualEffectView*)toolbar{
    if (_toolbar==nil) {
        if (KIsiPhoneX) {
            _toolbar=[[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
            _toolbar.frame=CGRectMake(0, self.view.frame.size.height-64,self.view.frame.size.width, 64);
        }else{
            _toolbar=[[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
            _toolbar.frame=CGRectMake(0, self.view.frame.size.height-44,self.view.frame.size.width, 44);
        }
    }
    return _toolbar;
}
-(UICollectionView*)collectionView{
    if (_collectionView==nil) {
        UICollectionViewFlowLayout*layout=[[UICollectionViewFlowLayout alloc]init];
        _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height-self.toolbar.frame.size.height) collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor=[UIColor whiteColor];
        [_collectionView registerClass:[LHImageViewCell class] forCellWithReuseIdentifier:kLHImagePickerCellIdentifier];
        [_collectionView registerClass:[LHReusableFooterView class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                   withReuseIdentifier:kLHImagePickerReuseFooterViewIdentifier];
    }
    return _collectionView;
}
-(LHCustomTitleView*)chooseTitleView{
    if (_chooseTitleView==nil) {
        _chooseTitleView=[[LHCustomTitleView alloc]initWithFrame:CGRectMake(0, 0, 90, 44) andDelegate:self];
    }
    return _chooseTitleView;
}
-(NSMutableArray<PHAsset*>*)dataSourceArray{
    if (_dataSourceArray==nil) {
        _dataSourceArray=[NSMutableArray array];
    }
    return _dataSourceArray;
}
- (NSMutableArray *)selectedAssetArray{
    if (!_selectedAssetArray) {
        _selectedAssetArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectedAssetArray;
}
#pragma mark - 视图加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    [LHCameraAuthoritymanager lh_requestUserAuthorizationPhotosWith:^(PHAuthorizationStatus status) {
        if (status==PHAuthorizationStatusAuthorized) {
            [self configSubviews];
        }else{
            [self userHasNoAuthority:@"我们无权限访问相册哦，请到设置中开启权限" andIsPhoto:YES];
        }
    }];
    
}
#pragma mark - 初始化子视图
-(void)configSubviews{
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationItem.titleView=self.chooseTitleView;
    [self.navigationItem setLeftBarButtonItem:[UIBarButtonItem  initWithTitle:@"取消" titleColor:[UIColor orangeColor] target:self action:@selector(cancelBtnClick)] animated:YES];
    self.allowMaxSelectedImageCount=self.allowMaxSelectedImageCount>0?self.allowMaxSelectedImageCount:3;
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.toolbar];
    [self.toolbar.contentView addSubview:self.nextStepBtn];
    self.dataSourceArray=[LHImagePickerManager lh_getAssetInPhotoAblumWithAscending:YES andSortDescriptorKey:@"creationDate" andMediaType:PHAssetMediaTypeImage];
    [self.collectionView reloadData];
}
#pragma mark - LHCustomTitleViewDelegate
-(void)lh_customNavTitleBtnDidiClick:(LHNavTitleChooseButton *)titleBtn andSelectedTitleBtnStatus:(TitleBtnStatus)status{
    if (status==TitleBtnStatusUp) {
        NSLog(@"箭头向上");
    }else{
        NSLog(@"箭头向下");
    }
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSourceArray.count+1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LHImageViewCell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:kLHImagePickerCellIdentifier forIndexPath:indexPath];
    if (cell.delegate==nil) {
        cell.delegate=self;
    }
    if (indexPath.row==0) {
        cell.assetModel=nil;
    }else{
        cell.assetModel=self.dataSourceArray[indexPath.row-1];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(([UIScreen mainScreen].bounds.size.width-10)/4, ([UIScreen mainScreen].bounds.size.width-10)/4);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 2, 0, 2);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 2.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0f;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"indexPath.row=%ld",indexPath.row);
}
-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionFooter){
        LHReusableFooterView*view=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kLHImagePickerReuseFooterViewIdentifier forIndexPath:indexPath];
        view.textLabel.text=[NSString stringWithFormat:@"总共%ld张照片",[LHImagePickerManager lh_getAssetCountWithmediaType:PHAssetMediaTypeImage]];
        return  view;
    }
    return  nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake([UIScreen mainScreen].bounds.size.width,44);
}

#pragma mark - LHImageViewCellDelegate
-(void)lh_LHImageViewCellDidSelectedAsset:(LHImageViewCell *)cell{
    NSLog(@"当前已选择%ld张图片",(long)self.selectedAssetArray.count+1);
    if (self.selectedAssetArray.count+1>self.allowMaxSelectedImageCount) {
        NSLog(@"最多选择%ld涨图片",(long)self.allowMaxSelectedImageCount);
        cell.isSelected = NO;
        return ;
    }
    PHFetchResult*resultArray=[PHAsset fetchAssetsWithLocalIdentifiers:@[cell.assetModel.localIdentifier] options:nil];
    [resultArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[PHAsset class]] && obj) {
            [self.selectedAssetArray addObject:obj];
        }
    }];
    self.nextStepBtn.hidden = (self.selectedAssetArray.count<=0);
    [self.nextStepBtn setTitle:[NSString stringWithFormat:@"下一步(%ld)",self.selectedAssetArray.count] forState:UIControlStateNormal];
    cell.isSelected = YES;
}
-(void)lh_LHImageViewCellDidDeselectedAsset:(LHImageViewCell *)cell{
    PHFetchResult*resultArray=[PHAsset fetchAssetsWithLocalIdentifiers:@[cell.assetModel.localIdentifier] options:nil];
    [resultArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[PHAsset class]] && obj) {
            if (self.selectedAssetArray.count>0) {
                [self.selectedAssetArray removeObject:obj];
            }
        }
    }];
    self.nextStepBtn.hidden = (self.selectedAssetArray.count<=0);
    [self.nextStepBtn setTitle:[NSString stringWithFormat:@"下一步(%ld)",self.selectedAssetArray.count] forState:UIControlStateNormal];
    cell.isSelected = NO;
}
/** 点击使用相机拍照 */
-(void)lh_LHImageViewCellPhotoBtnDidSelect:(LHImageViewCell *)cell{
    
    if (self.selectedAssetArray.count+1>self.allowMaxSelectedImageCount) {
        NSLog(@"最多选择%ld涨图片",(long)self.allowMaxSelectedImageCount);
        cell.isSelected = NO;
        return ;
    }
    
    [LHCameraAuthoritymanager  lh_requestUserAuthorizationCameraWith:^(AVAuthorizationStatus status) {
        NSLog(@"status=%ld",(long)status);
        if (status==AVAuthorizationStatusAuthorized) {
            [self takePhoto];
        }else{
            [self userHasNoAuthority:@"我们无权限使用相机哦，请到设置中开启权限" andIsPhoto:NO];
        }
    }];
}
#pragma mark - 拍照
-(void)takePhoto{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
            UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
            pickerController.allowsEditing = NO;
            pickerController.delegate = self;
            pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerController animated:YES completion:^{
            }];
        }else{
            [self userHasNoAuthority:@"当前设备后置摄像头无法正常开启或者已损坏" andIsPhoto:NO];
        }
    }
    
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [LHImagePickerManager lh_savePhotoAlbum:image andCompletion:^(BOOL success, NSError * _Nonnull error) {
        if (success) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                if (self.delegate && [self.delegate respondsToSelector:@selector(imagePickerController:didSelectAssets:isSource:)]) {
                    [self.delegate imagePickerController:self didSelectAssets:self.selectedAssetArray isSource:NO];
                }
            });
        }else{
            [self userHasNoAuthority:error.localizedDescription andIsPhoto:NO];
        }
    }];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 相机相册权限提示弹窗
-(void)userHasNoAuthority:(nullable NSString*)contentStr andIsPhoto:(BOOL)photo{
    UIAlertController*vc=[UIAlertController alertControllerWithTitle:@"温馨提示" message:contentStr preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction*action=[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (photo) {
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
    }];
    [vc addAction:action];
    [self presentViewController:vc animated:YES completion:^{
        
    }];
}
#pragma mark - 取消按钮点击事件
-(void)cancelBtnClick{
    if (self.delegate && [self.delegate respondsToSelector:@selector(imagePickerControllerDidCancel:)]) {
        [self.delegate imagePickerControllerDidCancel:self];
    }
}
#pragma mark - 下一步按钮点击
-(void)nextStepBtnDidClick:(UIButton*)btn{
    if ([_delegate respondsToSelector:@selector(imagePickerController:didSelectAssets:isSource:)]) {
        [_delegate imagePickerController:self
                         didSelectAssets:self.selectedAssetArray
                                isSource:NO];
    }
}
@end
